<template>
    <van-sticky z-index="100">
        <van-nav-bar title="购物车" left-text="返回" left-arrow @click-left="onBack" v-if="action == 'cart'" />
        <van-nav-bar title="购物车" v-else />
    </van-sticky>

    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
        <van-list
            v-model:loading="loading"
            :finished="finished"
            finished-text="没有更多了"
            @load="onLoad"
        >
            <!-- 复选框组 -->
            <van-checkbox-group v-model="checkedArr" ref="checkboxGroup" v-for="item in CartList" :key="item.id">
                <!-- 侧滑块 -->
                <!-- <van-swipe-cell v-for="item in CartList" :key="item.id"> -->
                    <!-- 商品卡片 -->
                    <van-card
                        :price="item.total"
                        :title="item.product.name"
                        class="goods-card"
                    >
                        <!-- 图片 -->
                        <template #thumb>
                            <van-checkbox :name="item.id" @click="onChecked"></van-checkbox>
                            <img :src="item.product.thumb_cdn" alt="" @click="toInfo(item.proid)">
                        </template>
                        <!-- 数量 -->
                        <template #num>
                            <van-stepper v-model="item.nums" :max="item.product.stock" @change="onChange(item.id,item.nums)" theme="round" button-size="22" disable-input />
                        </template>

                        <!-- 描述 -->
                        <template #desc>
                            <span>商品单价：￥{{ item.price }}</span>
                        </template>

                        <template #footer>
                            <van-button size="mini"  type="danger" @click="onDelete(item.id)">删除</van-button>
                            <!-- <van-button size="mini">按钮</van-button> -->
                        </template>
                    </van-card>
                    <!-- <template #right>
                        <van-button square text="删除" type="danger" class="delete-button" />
                    </template> -->
                <!-- </van-swipe-cell> -->

            </van-checkbox-group>
        </van-list>
    </van-pull-refresh>
    
    <van-submit-bar :price="total" :class="action ? '' : 'submit-bar'"  button-text="提交订单" @submit="onSubmit">
        <van-checkbox v-model="checked" @click="onCheckedAll">全选</van-checkbox>
    </van-submit-bar>


    <Footer v-if="!action" />
</template>

<script setup>
import Footer from '@/components/common/Footer.vue';
import { getCurrentInstance, ref, reactive, computed } from 'vue';

const { proxy } = getCurrentInstance();
const business = reactive(proxy.$cookies.get('business') ? proxy.$cookies.get('business') : {});
const action = ref(proxy.$route.query.action ? proxy.$route.query.action : '');
const refreshing = ref(false);
const loading = ref(false);
const finished = ref(false);
const checkedArr = ref([]);
const checked = ref(false);
const CartList = ref([]);
const CartCount = ref(0);
const page = ref(1);
const limit = ref(10);
const checkboxGroup = ref(null);

// 下拉刷新
const onRefresh = () => {
    CartList.value = [];
    page.value = 1;
    loading.value = true;
    refreshing.value = true;
    
    onLoad();
}

// 上拉加载
const onLoad = () => {

    if(!refreshing.value && CartList.value.length < CartCount.value)
    {
        page.value = page.value + 1;
    }

    if(refreshing.value)
    {
        setTimeout(() => {
            refreshing.value = false
        },1500);
    }

    setTimeout(getCartData,1500);
}

// 获取购物车的数据
const getCartData = async () => {
    let data = {
        busid:business.id,
        page:page.value,
        limit:limit.value
    }

    let result = await proxy.$api.CartIndex(data);

    if(result.code === 0)
    {
        proxy.$showNotify({
            type:'warning',
            message:result.msg,
            duration:1500,
            onClose:() => {
                finished.value = true;
            }
        });

        return;
    }

    finished.value = false;
    loading.value = false;

    let Data = result.data;

    CartList.value = CartList.value.concat(Data.list);
    CartCount.value = Data.count;

    if(CartCount.value == CartList.value.length)
    {
        finished.value = true;
        loading.value = false;
        return;
    }

}

// 更新购物车的数量
const onChange = async (id,nums) => {
    let data = {
        busid:business.id,
        id:id,
        nums:nums
    }

    let result = await proxy.$api.UpdateProductNumber(data);

    if(result.code === 0)
    {
        proxy.$showNotify({
            type:'warning',
            message:result.msg,
            duration:1500,
        });

        return;
    }

    for(let i in CartList.value)
    {
        if(CartList.value[i].id == id)
        {
            let total = nums * CartList.value[i].price;
            CartList.value[i].total = total.toFixed(2);
        }
    }
}

const onCheckedAll = () => {

    if(CartList.value.length == 0)
    {
        return;
    }

    checkboxGroup.value.toggleAll();
}

const onChecked = () => {
    if(checkedArr.value.length === CartList.value.length)
    {
        checked.value = true;
    }else{
        checked.value = false;
    }
}

const toInfo = (proid) => {
    proxy.$router.push({path:'/product/product/info',query:{proid:proid}});
    return;
}

const total = computed(() => {
    let total = 0;

    if(checkedArr.value.length > 0)
    {
        for(let item of CartList.value)
        {
            if(checkedArr.value.includes(item.id))
            {
                total += parseFloat(item.total);
            }
        }
    }


    return total * 100;
});

// 把购物车的商品到商品结算
const onSubmit = () => {
    if(checkedArr.value.length <= 0)
    {
        proxy.$showNotify({
            type:'warning',
            message:'请选择需要结算商品',
            duration:1500
        });

        return;
    }

    proxy.$router.push({path:'/product/cart/confirm',query:{cartids:checkedArr.value.join(',')}});
}

const onDelete = (id) => {

    proxy.$showConfirmDialog({
        title:'删除',
        message:'是否确认删除？'
    }).then(async (res) => {
        let data = {
            busid:business.id,
            id:id
        }

        let result = await proxy.$api.CartDel(data);

        if(result.code === 1)
        {
            proxy.$showNotify({
                type:'success',
                message:result.msg,
                duration:1500,
                onClose:() => {
                    onRefresh();
                }
            });

            return;
        }else{
            proxy.$showNotify({
                type:'warning',
                message:result.msg,
                duration:1500
            });

            return;
        }
    }).catch((err) => {
        console.log('取消操作')
    });
}

const onBack = () => {
    proxy.$router.go(-1);
}

</script>

<style>
.submit-bar{
    bottom: 50px;
}

.bar{
    bottom: 55px;
}

.goods-card {
    margin: 0;
    background-color: #fff;
}

.delete-button {
    height: 100%;
}

.van-card__thumb{
    display: flex;
    width: auto;
}

.van-card__thumb img{
    width: 88px;
    margin-left: 5px;
}
</style>
